<?php
/**
 * Author:   tangxiaowen
 * Email:    846506584@qq.com
 * Date:     2019/4/22 0022
 * Describe: 滴滴风控
 */

namespace app\api\controller\didi;

use think\Log;
use think\Request;
use think\Controller;
use app\common\model\User;

class Didi extends Controller
{
    //滴滴模型号
    private static $modelName;
    //滴滴请求地址
    private static $url = 'http://47.93.185.26/risk/gzip/';

    public function __construct()
    {
        parent::__construct();

        //日志初始化保存地址
        $setPath = strtolower(request()->module().'/'.request()->controller().'/'.request()->action().'/');
        Log::init(['path' => LOG_PATH.$setPath, 'type' => 'file']);

        //初始化滴滴配置
        $this->initDidiConfig();
    }

    /**
     * 测试方法
     */
    public function test()
    {
        $result = $this->didi(1070,'2019-04-22 10:20:55');
        dump($result);
    }

    /**
     * 请求滴滴风控地址并获取滴滴结果
     * @param integer $userId 用户ID
     * @param datetime $ApplyTime 申请借款时间
     * @param string $phoneOs 用户手机手机操作系统 android/ios
     * @param string $deviceId 设备号 ios填idfa，android填imei
     * @param integer $firstLoan 用户是否首贷 1是 0复贷
     */
    public function didi($userId,$ApplyTime,$firstLoan = 1,$phoneOs = '',$deviceId = '')
    {
        //获取用户数据 用户信息 社交信息 魔蝎原始数据 魔蝎运营商数据 新颜原始数据 新颜运营商数据
        $userModelObj = new User();
        $userInfo = $userModelObj->getIdUserInfo($userId);
        $social = $userModelObj->getUserSocial($userId);
        $moxieData = $userModelObj->getMoXieData($userId);
        $moxieReport = $userModelObj->getMoXieReport($userId);
        $xinyanData = $userModelObj->getXinYanData($userId);
        $xinyanReport = $userModelObj->getXinYanReport($userId);
        $youdunData = $userModelObj->getYouDunData($userId);

        $phoneList =json_decode($social['Phonelist'],true);
        //组合请求参数请求滴滴风控并获取处理结果返回
        $temp = [
            'model_name' => self::$modelName,          //分配的模型号，对接时候进行分配
            'first_loan' => $firstLoan,
            'apply_time' => $ApplyTime,                //申请借款时间
            'mobile'     => $userInfo['Mobile']??'',   //手机号
            'name'       => $userInfo['TrueName']??'', //姓名
            'idcard'     => $userInfo['IDCard']??'',   //省份证号
            'user_address' => empty($social['address'])?$social['address']:'杭州' . empty($social['ad_detail'])?$social['ad_detail']:'杭州西湖区1栋',
            'phone_os'   => $phoneOs,
            'device_id'  => $deviceId,
            'e_contacts' => [                          //紧急联系人 2位
                [
                    'contact_name'  => $social['person_one']??'',
                    'contact_phone' => $social['person_one_mobile']??'',
                ],
                [
                    'contact_name'  => $social['person_two']??'',
                    'contact_phone' => $social['person_two_mobile']??'',
                ]
            ],
            'carrier_data' => [
                'mx_raw'   => $moxieData??'',              //魔蝎原始数据
                'mx_report'=> $merchant['ReportData']??'', //魔蝎报告
                "xinyan_raw" => $xinyanData,               //新颜原始数据
                "xinyan_report" => $xinyanReport,          //新颜报告
            ],
            'contact'      => $phoneList,
            'udcredit_portrait' => $youdunData,            //有盾报告数据
        ];
        $param1 = json_encode($temp,JSON_UNESCAPED_UNICODE);
        $param2 = gzencode($param1);
        $result1 = $this->curlRequest(self::$url,$param2);
        $resArray = json_decode($result1,true);
        if($resArray['score'] == 0){
            $resArray['score'] = 0;
            $result3 = json_encode($resArray,JSON_UNESCAPED_UNICODE);
        }else{
            $resArray['score'] = sprintf('%.2f',$resArray['score']);
            $result3 = json_encode($resArray,JSON_UNESCAPED_UNICODE);
        }
        return $result3;
    }

    /**
     * 获取滴滴配置信息
     * @return array
     */
    private function initDidiConfig()
    {
        $data = db('sys_integrate')->alias('i')
            ->join('xb_sys_inteparameter n','i.ID = n.IntegrateID')
            ->where(['i.EName' => 'didi'])
            ->find();

        if(!$data){
            returnErrorResult('尚未配置滴滴数据');
        }

        if(!isset($data['ParaName']) || empty($data['ParaName'])){
            returnErrorResult('尚未配置模型号');
        }elseif(!isset(self::$url) || empty(self::$url)){
            returnErrorResult('尚未配置滴滴请求地址');
        }

        self::$modelName  = $data['ParaValue'];
    }

    /**
     * 创建curl请求
     * @param url $url 请求地址
     * @param array $param 请求数据
     */
    public function curlRequest($url,$param)
    {
        $headers[] = "Content-Type:application/json";
        $culObj = curl_init();
        //设置请求的curl
        curl_setopt($culObj, CURLOPT_URL, $url);
        //不输出文件头(直接获取内容部分)
        curl_setopt($culObj, CURLOPT_HEADER, false);
        //设置curl请求方式
        curl_setopt($culObj, CURLOPT_POST, true);
        //设置请求的参数
        curl_setopt($culObj, CURLOPT_POSTFIELDS, $param);
        //将curl_exec()获取的信息以字符串返回，而不是直接输出。
        curl_setopt($culObj, CURLOPT_RETURNTRANSFER, true);
        //禁止 cURL 验证对等证书（peer's certificate）
        curl_setopt($culObj, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($culObj, CURLOPT_HTTPHEADER, $headers);
        //允许Curl函数执行的最长秒数。这里设置为30秒
        curl_setopt($culObj, CURLOPT_TIMEOUT, 30);
        $result = curl_exec($culObj);
        curl_close($culObj);
        return $result;
    }

}